package com.gzy.net_app.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import com.bumptech.glide.Glide;
import com.gzy.net_app.MainActivity;
import com.gzy.net_app.api.ApiService;
import com.gzy.net_app.application.AppContext;
import com.gzy.net_app.bean.CodeBean;
import com.gzy.net_app.databinding.ActivityLoginBinding;
import com.gzy.net_app.ui.BaseActivity;
import com.gzy.network.NetworkApi;
import com.gzy.network.observer.BaseObserver;
import com.gzy.network.utils.KLog;
import com.orhanobut.hawk.Hawk;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import org.json.JSONException;
import org.json.JSONObject;

import static com.gzy.net_app.api.ApiService.mBaseUrl;

public class LoginActivity extends BaseActivity<ActivityLoginBinding> {

  public static final String TAG = LoginActivity.class.getSimpleName();
  public String code;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    initData();
  }

  private void initData() {

    if (!TextUtils.isEmpty(Hawk.get("username"))) {
      binding.etAccount.setText(Hawk.get("username"));
    }
    if (!TextUtils.isEmpty(Hawk.get("pwd"))) {
      binding.etPwd.setText(Hawk.get("pwd"));
    }
    //获取验证码
    showCodePicture();

    binding.btnLogin.setOnClickListener(view -> login());
    binding.ivCodePicture.setOnClickListener(view -> showCodePicture());
    binding.tvSignin.setOnClickListener(view ->  AppContext.showToast("此功能暂未开发"));
    binding.tvForgetPwd.setOnClickListener(view -> AppContext.showToast("此功能暂未开发"));
  }

  //登录处理
  private void login() {

    String username = binding.etAccount.getText().toString().trim();
    String password = binding.etPwd.getText().toString().trim();
    String etCode = binding.etCode.getText().toString().trim();
    if (TextUtils.isEmpty(username)) {
      AppContext.showToast("用户名不能为空，请输入用户名");
      return;
    }
    if (TextUtils.isEmpty(password)) {
      AppContext.showToast("密码不能为空，请输入密码");
      return;
    }
    if (TextUtils.isEmpty(etCode)) {
      AppContext.showToast("验证码不能为空，请输入验证码");
      return;
    }

    //将用户名和密码保存
    Hawk.put("username", username);
    Hawk.put("pwd", password);

    JSONObject jsonData = new JSONObject();
    try {
      jsonData.put("login", username);
      jsonData.put("password", password);
      jsonData.put("randomCode", code);
      jsonData.put("validateCode", etCode);
    } catch (JSONException e) {
      e.printStackTrace();
    }

    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData.toString());

    NetworkApi.createService(ApiService.class)
        .loginApi(requestBody)
        .compose(NetworkApi.applySchedulers(new BaseObserver<ResponseBody>() {
          @Override public void onSuccess(ResponseBody responseBody) {
            String result = AppContext.doJson(responseBody);
            String token = null;
            try {
              JSONObject jsonObject = new JSONObject(result);
              token = jsonObject.getString("token");
            } catch (JSONException e) {
              e.printStackTrace();
            }
            if (token != null) {
              Hawk.put("token", token);
              KLog.d(TAG, "登录返回结果token：" + token);
              AppContext.showToast("登录成功");

              Intent intent = new Intent(LoginActivity.this, MainActivity.class);
              startActivity(intent);
              removeALLActivity();//执行移除所以Activity方法
            } else {
              AppContext.showToast(result);
              KLog.d(TAG, "登录返回结果为空");
            }
            showCodePicture();
          }
          //获取验证码

          @Override public void onFailure(Throwable e) {
            if (e.getMessage().contains("401")) {
              AppContext.showToast("用户名密码错误");
            }
            if (e.getMessage().contains("400")) {
              AppContext.showToast("验证码输入错误");
            }
            KLog.e(TAG, e.getMessage());
            showCodePicture();
          }
        }));
  }

  //展示验证码
  private void showCodePicture() {

    NetworkApi.createService(ApiService.class)
        .getCodePicture()
        .compose(NetworkApi.applySchedulers(new BaseObserver<CodeBean>() {
          @Override
          public void onSuccess(CodeBean codeBean) {
            code = codeBean.getRandomCode();
            String imgUrl = codeBean.getImageUrl();
            if (!TextUtils.isEmpty(imgUrl)) {
              KLog.d(TAG, "图片地址为:" + imgUrl);
              KLog.d(TAG, "随机吗：:" + code);
              Glide.with(LoginActivity.this).load(mBaseUrl + imgUrl).into(binding.ivCodePicture);
            } else {
              KLog.d(TAG, "图片地址为空");
            }
          }

          @Override
          public void onFailure(Throwable e) {
            KLog.d(TAG, "访问失败");
            KLog.e(TAG, e.toString());
          }
        }));
  }

  @Override public void onBackPressed() {
    super.onBackPressed();
    finish();
  }
}